package net.vinote.smart.platform.service.handler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.mail.Message;

import net.vinote.smart.platform.comm.DateFunction;
import net.vinote.smart.platform.exception.PlatformException;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.module.mail.EmailReceive;
import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.bean.User;
import net.vinote.smart.platform.service.bean.User.Email;
import net.vinote.smart.platform.service.dw.handler.HandlerPerimissionAnnotation;
import net.vinote.smart.platform.service.dw.handler.VirtualCommonHandler;
import net.vinote.smart.platform.service.enumerate.CodeCatalogEnum;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;
import net.vinote.smart.platform.service.util.Permission.PermissionRelation;

import org.json.JSONObject;

@HandlerPerimissionAnnotation(
		virtual = @Permission(
				value = PermissionEnum.SMART_DISABLE,
				PermissionRelation = PermissionRelation.NOT))
public class EmailListVirtualHandler extends VirtualCommonHandler {

	@Override
	public List<BizObject> initDataList() {
		User user = (User) request.getSession().getAttribute("user");
		Email email = user.getEmail();
		if (email == null) {
			throw new PlatformException("当前用户还未进行邮箱配置!");
		}
		JSONObject serverJson = new JSONObject(SRE
				.getCodeItems(CodeCatalogEnum.EmailConfig.getCode())
				.get(email.getServer()).getAttr01());
		List<BizObject> list = new ArrayList<BizObject>();
		JSONObject cfgJson = serverJson.getJSONObject(email
				.getReceiveProtocol());
		EmailReceive receive = new EmailReceive();
		try {
			receive.connect(
					email.getUser(),
					email.getPassword(),
					cfgJson.getString("host"),
					email.isReceiveSSL() ? cfgJson.getString("ssl") : cfgJson
							.getString("port"), email.getReceiveProtocol(),
					email.isReceiveSSL());
			Message[] msgs = receive.list();
			for (Message msg : msgs) {
				BizObject bo = new BizObject();
				bo.setAttribute("from", Arrays.toString(msg.getFrom()));
				bo.setAttribute("subject", msg.getSubject());
				bo.setAttribute("sentDate", DateFunction.getDate(
						msg.getSentDate(), DateFunction.DEFAULT_FORMAT));
				bo.setAttribute("receivedDate", DateFunction.getDate(
						msg.getReceivedDate(), DateFunction.DEFAULT_FORMAT));
				list.add(bo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			receive.close();
		}
		return list;
	}

	@Override
	public int initDataCount() {
		// TODO Auto-generated method stub
		return super.initDataCount();
	}

}
